package servlet;

import model.Goods;
import model.Order;
import model.User;
import service.GoodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "goods_collect",urlPatterns = "/goods_collect")
public class GoodsBuyServlet extends HttpServlet {
    private GoodsService gService = new GoodsService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Order o = null;
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            request.setAttribute("failMsg", "请先登录！");
            request.getRequestDispatcher("/user_login.jsp").forward(request, response);
            return;
        }
        //若购物车不为空，则获取购物车对象，若为空，则创建一个购物车对象
        if(request.getSession().getAttribute("order") != null) {
            o = (Order) request.getSession().getAttribute("order");
        }else {
            o = new Order();
            request.getSession().setAttribute("order", o);
        }
        //获取商品id
        int goodsid = Integer.parseInt(request.getParameter("goodsid"));
        Goods goods = gService.getGoodsById(goodsid);
        o.addGoods(goods);
        request.setAttribute("gcs", "商品收藏成功！");
        request.getRequestDispatcher("/goods_detail?productId="+goodsid).forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
